#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:homework8_4.py
# author:wmf
# datetime:2021/5/8 23:29
# software: PyCharm
'''
this is function description
'''
# import module your need

# 4 多进程通讯：
#   编写一个简单的聊天程序；其中一个进程发送文字聊天消息（从键盘输入文字消息）；  另外一个进程接收并打印消息；

from multiprocessing import Process, Queue
import os, time, random


# 写数据进程执行的代码:
def write(q, info):
    print('Process to write: %s' % os.getpid())
    print('发送信息%s' % info)
    q.put(info)
    time.sleep(random.random())


# 读数据进程执行的代码:
def read(q):
    print('Process to read: %s' % os.getpid())
    while True:
        value = q.get(True)
        print('送到信息%s' % value)


if __name__ == '__main__':
    info = ''
    while info != "end":
        info = input("请发送消息:")
        # 父进程创建Queue，并传给各个子进程：
        q = Queue()
        pw = Process(target=write, args=(q, info,))
        pr = Process(target=read, args=(q,))
        # 启动子进程pw，写入:
        pw.start()
        # 启动子进程pr，读取:
        pr.start()
        # 等待pw结束:
        pw.join()
        # pr进程里是死循环，无法等待其结束，只能强行终止:
        pr.terminate()
